package com.wenjing.xiaoyun.chat.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wenjing.xiaoyun.chat.mapper.ChatSessionMapper;
import com.wenjing.xiaoyun.common.entity.ChatSession;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ChatSessionService extends ServiceImpl<ChatSessionMapper, ChatSession> {
    
    /**
     * 获取用户的所有会话
     */
    public List<ChatSession> getUserSessions(Long userId) {
        QueryWrapper<ChatSession> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .orderByDesc("update_time");
        return list(queryWrapper);
    }
    
    /**
     * 创建新会话
     */
    public ChatSession createSession(Long userId, String sessionName) {
        ChatSession session = new ChatSession();
        session.setUserId(userId);
        session.setSessionName(sessionName);
        session.setCreateTime(LocalDateTime.now());
        session.setUpdateTime(LocalDateTime.now());
        save(session);
        return session;
    }
    
    /**
     * 删除会话
     */
    public void deleteSession(Long sessionId, Long userId) {
        QueryWrapper<ChatSession> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("session_id", sessionId)
                   .eq("user_id", userId);
        remove(queryWrapper);
    }
    
    /**
     * 更新会话名称
     */
    public ChatSession updateSessionName(Long sessionId, Long userId, String newName) {
        QueryWrapper<ChatSession> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("session_id", sessionId)
                   .eq("user_id", userId);
        
        ChatSession session = getOne(queryWrapper);
        if (session != null) {
            session.setSessionName(newName);
            session.setUpdateTime(LocalDateTime.now());
            updateById(session);
        }
        return session;
    }
} 